import datetime
import re
from random import randint

from django.shortcuts import render
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.exceptions import AuthenticationFailed
from django.db.models import Count

from apps.community.MyPaginations import TagListPager
from apps.community.comserializer import UserSerializer, NewsSerializer, NewestSerializer, ReplaySerializer, \
    Replay2Serializer, PostingSerializer, TopicSerializer
from apps.community.myimg import my_upload
from common.response_code import RET, error_map
from apps.community.DPaginations import TopicListPager
from apps.community.comserializer import ReminderbookkeepingSerializer, FansSerializer, CommentSerializer
from db.models import XlzNews, XlzAttention, XlzUser, XlzReplay, XlzReplay2, XlzReport, XlzImages, XlzRemind, XlzLike
from db.models import XlzTopic, XlzCollect
# Create your views here.

from libs.userinfo import userinfo


# 社区-关注
class AttentionView(GenericAPIView):
    queryset = XlzAttention.objects.all()
    serializer_class = NewsSerializer
    pagination_class = TagListPager

    def get(self, request):
        try:
            # 数据查询
            queryset = XlzAttention.objects.filter(fans_id=request.user.id)
            att_list = []
            for que in queryset:
                att_list.append(que.user_id)
            news_queryset = XlzNews.objects.filter(user_id__in=att_list)
            # 根据指定页数序列化
            page = self.paginate_queryset(news_queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            # 序列化
            attention_data = self.get_serializer(news_queryset, many=True)
            return Response({
                'code': 200,
                'msg': '请求成功',
                'data': attention_data.data,
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.ATTENTION_ERROR, "msg": error_map[RET.ATTENTION_ERROR]})

        # 点赞
    def patch(self, request):
        try:
            uid = request.user.id
            nid = request.data.get('news_id')
            news_que = XlzNews.objects.filter(id=nid)
            # 判断该动态id是否存在
            if news_que:
                news = news_que.first()
                # 判断点赞表中是否存在该数据
                like_que = XlzLike.objects.filter(user_id=uid, new_id=nid)
                if like_que:
                    status = like_que[0].status
                    # 表示未点赞
                    if status == 0:
                        like_que.update(status=1)
                        news.like_num = news.like_num + 1
                        news.save()
                        return Response({
                            'code': 200,
                            'msg': '点赞成功',
                            'data': {},
                        })
                    elif status == 1:
                        like_que.update(status=0)
                        news.like_num = news.like_num - 1
                        news.save()
                        return Response({
                            'code': 200,
                            'msg': '已取消点赞',
                            'data': {},
                        })
                    else:
                        raise AuthenticationFailed({"code": RET.NEWS_ERROR, "msg": error_map[RET.NEWS_ERROR]})
                else:
                    # 不存在则创建该数据，并高亮点赞状态(1：已点赞过)
                    XlzLike.objects.create(user_id=uid, new_id=nid, status=1)
                    news.like_num = news.like_num + 1
                    news.save()
                    return Response({'code': 200, 'msg': '点赞成功'})
            else:
                raise AuthenticationFailed({"code": RET.NEWS_ERROR, "msg": error_map[RET.NEWS_ERROR]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-关注-评论
class CommentView(GenericAPIView):
    queryset = XlzNews.objects.all()
    serializer_class = NewsSerializer

    def get(self, request):
        try:
            cid = request.query_params.get("comment_id", None)  # 动态消息id
            # 数据查询
            news_queryset = XlzNews.objects.filter(id=cid)
            if news_queryset:
                replay_queryset = XlzReplay.objects.filter(comment_id=cid)

                comment_list = []
                for comment in replay_queryset:
                    comment_list.append(comment.id)
                replay2_queryset = XlzReplay2.objects.filter(comment_id__in=comment_list)

                # 序列化
                news_data = self.get_serializer(news_queryset, many=True)
                replay_data = ReplaySerializer(replay_queryset, many=True)
                replay2_data = Replay2Serializer(replay2_queryset, many=True)
                return Response({
                    'code': 200,
                    'msg': '请求成功',
                    'data': {
                        'data': news_data.data,
                        'comment': replay_data.data,
                        'comment_in': replay2_data.data,
                    },
                })
            else:
                raise AuthenticationFailed({"code": RET.NEWS_ERROR, "msg": error_map[RET.NEWS_ERROR]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})

    # 添加评论
    def post(self, request):
        try:
            user_id = request.user.id
            content = request.data.get('content')  # 评论内容
            news_id = request.data.get('news_id')  # 动态id
            # 判断动态id不能为空,且动态消息表有对应的id
            if news_id is None or not XlzNews.objects.filter(id=news_id):
                raise AuthenticationFailed({"code": RET.NODATA, "msg": error_map[RET.NODATA]})
            if content:  # 可以在此处添加过滤敏感字符
                XlzReplay.objects.create(user_id=user_id, content=content, comment_id=news_id)
                return Response({'code': 200, 'msg': '评论添加成功'})
            else:
                raise AuthenticationFailed({"code": RET.NODATA, "msg": error_map[RET.NODATA]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})

    # 转发
    def patch(self, request):
        try:
            cid = request.data.get('comment_id', None)
            news_queryset = XlzNews.objects.filter(id=cid)  # 动态id
            if news_queryset:
                news = news_queryset[0]
                news.transmit = news.transmit + 1
                news.save()
                return Response({
                    'code': 200,
                    'msg': '转发请求成功',
                    'data': {},
                })
            else:
                raise AuthenticationFailed({"code": RET.NEWS_ERROR, "msg": error_map[RET.NEWS_ERROR]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-关注-评论-子评论
class ReviewView(APIView):
    def post(self, request):
        try:
            user_id = request.user.id
            content = request.data.get('content')  # 评论内容
            comment_id = request.data.get('comment_id')  # 动态id
            # 判断动态id不能为空,且动态消息表有对应的id
            if not XlzNews.objects.filter(id=comment_id):
                raise AuthenticationFailed({"code": RET.NODATA, "msg": error_map[RET.NODATA]})
            if content:  # 可以在此处添加过滤敏感字符
                XlzReplay2.objects.create(user_id=user_id, content=content, comment_id=comment_id)
                return Response({'code': 200, 'msg': '评论添加成功'})
            else:
                raise AuthenticationFailed({"code": RET.NODATA, "msg": error_map[RET.NODATA]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-评论-陌生人
class OtherUserView(GenericAPIView):
    queryset = XlzUser.objects.all()
    serializer_class = UserSerializer

    def get(self, request):
        try:
            uid = request.user.id
            username = request.query_params.get('username', None)  # 用户名
            # 获取数据
            other_user = XlzUser.objects.filter(username=username)
            if other_user:
                oid = other_user[0].id
                # 判断是否已关注
                attention = XlzAttention.objects.filter(user_id=oid).filter(fans_id=uid)
                is_attention = 1 if attention else 0
                # 调用封装好的函数
                clock, sum_day, sum_account = userinfo(other_user, uid)
                # 序列化
                user_data = self.get_serializer(other_user, many=True)
                return Response({
                    'code': 200,
                    'msg': '请求成功',
                    'data': {
                        'head': user_data.data,
                        'is_attention': is_attention,
                        'clock_day':  clock,
                        'sum_day': sum_day.days,
                        'sum_account': sum_account,
                    },
                })
            else:
                raise AuthenticationFailed({"code": RET.USERERR, "msg": error_map[RET.USERERR]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})

    # 举报
    def post(self, request):
        try:
            data = request.POST
            report = XlzReport()
            report.report_str = data.get('report')
            report.user_id = request.user.id
            # 举报的是用户
            if 'by_username' in data and 'news_id' not in data:
                username = data.get('by_username')
                other_user = XlzUser.objects.filter(username=username)
                if other_user:
                    report.by_user_id = other_user[0].id
                    report.save()
                    return Response({
                        'code': 200,
                        'msg': '举报请求成功',
                        'data': {},
                    })
                else:
                    raise AuthenticationFailed({"code": RET.USERERR, "msg": error_map[RET.USERERR]})
            # 举报的是用户动态
            elif 'by_username' not in data and 'news_id' in data:
                news_id = data.get('news_id')
                if XlzNews.objects.filter(id=news_id):
                    report.news_id = news_id
                    report.save()
                    return Response({
                        'code': 200,
                        'msg': '举报请求成功',
                        'data': {},
                    })
                else:
                    raise AuthenticationFailed({"code": RET.NEWS_ERROR, "msg": error_map[RET.NEWS_ERROR]})
            else:
                # 其他错误
                raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-评论-陌生人-帖子
class UserPostView(GenericAPIView):
    queryset = XlzNews.objects.all()
    serializer_class = NewsSerializer
    pagination_class = TagListPager

    def get(self, request):
        try:
            username = request.query_params.get('username')
            # 获取数据
            other_user = XlzUser.objects.filter(username=username)
            if other_user:
                oid = other_user[0].id
                news_queryset = XlzNews.objects.filter(user_id=oid)
                # 根据指定页数序列化
                page = self.paginate_queryset(news_queryset)
                if page is not None:
                    serializer = self.get_serializer(page, many=True)
                    return self.get_paginated_response(serializer.data)
                # 序列化
                news_data = self.get_serializer(news_queryset, many=True)

                return Response({
                    'code': 200,
                    'msg': '帖子查询请求成功',
                    'data': news_data.data,
                })
            else:
                raise AuthenticationFailed({"msg": RET.USERERR, "code": error_map[RET.USERERR]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-评论-陌生人-收藏
class CollectView(GenericAPIView):
    queryset = XlzNews.objects.all()
    serializer_class = NewsSerializer
    pagination_class = TagListPager

    def get(self, request):
        try:
            username = request.query_params.get('username')
            # 获取数据
            other_user = XlzUser.objects.filter(username=username)
            if other_user:
                oid = other_user[0].id
                user_que = XlzCollect.objects.filter(user_id=oid)
                news_list = []
                for news_obj in user_que:
                    news_list.append(news_obj.new_id)
                news_queryset = XlzNews.objects.filter(id__in=news_list)
                # 根据指定页数序列化
                page = self.paginate_queryset(news_queryset)
                if page is not None:
                    serializer = self.get_serializer(page, many=True)
                    return self.get_paginated_response(serializer.data)
                # 序列化
                news_data = self.get_serializer(news_queryset, many=True)

                return Response({
                    'code': 200,
                    'msg': '收藏查询请求成功',
                    'data': news_data.data,
                })
            else:
                raise AuthenticationFailed({"msg": RET.USERERR, "code": error_map[RET.USERERR]})
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-评论-陌生人-添加收藏
class AddCollectView(GenericAPIView):
    # 显示收藏状态
    def get(self, request):
        nid = request.query_params.get('news_id')
        try:
            nid = int(nid)
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})
        if not XlzNews.objects.filter(id=nid):
            raise AuthenticationFailed({"code": RET.NEWS_ERROR, "msg": error_map[RET.NEWS_ERROR]})
        uid = request.user.id
        collect_que = XlzCollect.objects.filter(new_id=nid, user_id=uid)
        if len(collect_que) == 1:
            if collect_que[0].is_delete == 0:
                return Response({
                    'code': 200,
                    'msg': '请求成功',
                    'data': 1,  # 收藏图标高亮
                })
            elif collect_que[0].is_delete == 1:
                return Response({
                    'code': 200,
                    'msg': '请求成功',
                    'data': 0,
                })
        else:
            return Response({'code': 200, 'msg': '请求成功', 'data': 0})

    # 添加收藏与移除删除
    def post(self, request):
        try:
            nid = int(request.POST.get('news_id'))
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})
        if not XlzNews.objects.filter(id=nid):
            raise AuthenticationFailed({"code": RET.NEWS_ERROR, "msg": error_map[RET.NEWS_ERROR]})
        uid = request.user.id
        collect_que = XlzCollect.objects.filter(new_id=nid, user_id=uid)
        # 判断该动态存在，并且该用户从未添加过该收藏,才执行加入收藏
        if len(collect_que) == 1:
            if collect_que[0].is_delete == 0:
                collect_que.update(is_delete=1)
                return Response({
                    'code': 200,
                    'msg': '请求成功,取消收藏',
                    'data': {},
                })
            else:
                collect_que.update(is_delete=0)
                return Response({
                    'code': 200,
                    'msg': '请求成功,已添加收藏',
                    'data': {},
                })
        elif len(collect_que) == 0:
            XlzCollect.objects.create(new_id=nid, user_id=uid)
            return Response({
                'code': 200,
                'msg': '请求成功,已添加收藏',
                'data': {},
            })
        else:
            raise AuthenticationFailed({"code": RET.DATAEXIST, "msg": error_map[RET.DATAEXIST]})


# 社区－推荐页
class RecommendView(GenericAPIView):
    queryset = XlzNews.objects.all()
    serializer_class = NewestSerializer
    pagination_class = TopicListPager

    def get(self, request):
        context = {
            "request": request,
        }
        # # 用户动态查询
        queryset = XlzNews.objects.all()
        news_list = []
        for que in queryset:
            news_list.append(que.user_id)
            news_queryset = XlzNews.objects.filter(user_id__in=news_list)
            page = self.paginate_queryset(news_queryset)
            if page is not None:
                serializer = self.get_serializer(page, context=context, many=True)
                return self.get_paginated_response(serializer.data)
            # 序列化
            news_data = self.get_serializer(news_queryset, context=context, many=True)
            return Response({
                'code': RET.OK,
                'msg': error_map[RET.OK],
                'data': {
                    'data': news_data.data,
                },
            })
        return Response({
            'code': error_map[RET.NODATA],
            'msg': RET.NODATA,
            'data': {
                'data': {},
            },
        })

    # 关注某用户
    def post(self, request):
        try:
            # 发表这条动态的用户
            username = request.POST.get('user_name')
            user = XlzUser.objects.get(username=username)
            # 获取被关注者的ｉｄ
            fans_id = request.user.id
            is_exits = XlzAttention.objects.filter(user_id=user.id, fans_id=fans_id)
            if user.id == fans_id:
                return Response({
                    'code': RET.CAN_NOT_YOURSELF,
                    'msg': error_map[RET.CAN_NOT_YOURSELF],
                    'data': {},
                })
            if is_exits:
                is_exits.delete()
                return Response({
                    'code': RET.UNFOLLOW,
                    'msg': error_map[RET.UNFOLLOW],
                    'data': {},
                })
            else:
                attention = XlzAttention.objects.create(user_id=user.id, fans_id=fans_id)
                return Response({
                    'code': RET.OK,
                    'msg': error_map[RET.OK],
                    'data': {},
                })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区－最新页
class NewestView(GenericAPIView):
    queryset = XlzNews.objects.all()
    serializer_class = NewestSerializer
    pagination_class = TagListPager

    def get(self, request):
        try:
            context = {
                "request": request,
            }
            # uid = request.user.id
            # 动态查询
            queryset = XlzNews.objects.order_by('-update_time')
            if queryset:
                page = self.paginate_queryset(queryset)
                if page is not None:
                    serializer = self.get_serializer(page, context=context, many=True)
                    return self.get_paginated_response(serializer.data)
                # 序列化
                news_data = self.get_serializer(queryset, context=context, many=True)
                return Response({
                    'code': RET.OK,
                    'msg': error_map[RET.OK],
                    'data': {
                        'data': news_data.data,
                    },
                })
            return Response({
                'code': error_map[RET.NODATA],
                'msg': RET.NODATA,
                'data': {
                    'data': {},
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})

    def post(self, request):
        try:
            # 发表这条动态的用户
            username = request.POST.get('user_name')
            user = XlzUser.objects.get(username=username)
            # 获取被关注者的ｉｄ
            fans_id = request.user.id
            is_exits = XlzAttention.objects.filter(user_id=user.id, fans_id=fans_id)
            if user.id == fans_id:
                return Response({
                    'code': RET.CAN_NOT_YOURSELF,
                    'msg': error_map[RET.CAN_NOT_YOURSELF],
                    'data': {},
                })
            if is_exits:
                is_exits.delete()
                return Response({
                    'code': RET.UNFOLLOW,
                    'msg': error_map[RET.UNFOLLOW],
                    'data': {},
                })
            else:
                attention = XlzAttention.objects.create(user_id=user.id, fans_id=fans_id)
                # attention.save()
                return Response({
                    'code': RET.OK,
                    'msg': error_map[RET.OK],
                    'data': {},
                })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区－发帖
class PostingView(APIView):

    def post(self, request):
        try:
            user_id = request.user.id
            try:
                topic_id = int(request.POST.get('topic_id'))
            except Exception as e:
                print(e)
                raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})
            content = request.POST.get('content')
            site_tag = request.POST.getlist('siteTag')
            brand_tag = request.POST.getlist('brandTag')
            diy_tag = request.POST.getlist('diyTag')
            site_location = request.POST.getlist('siteLocation')
            brand_location = request.POST.getlist('brandLocation')
            diy_location = request.POST.getlist('diyLocation')
            img_list = request.FILES.getlist('files')
            if topic_id:
                XlzNews.objects.create(user_id=user_id, topic_id=topic_id, content=content, transmit=0,
                                       like_num=0)
            elif topic_id == 0:
                XlzNews.objects.create(user_id=user_id, content=content, transmit=0, like_num=0)
            else:
                XlzNews.objects.create(user_id=user_id, content=content, transmit=0, like_num=0)
            # 获取最新的动态消息
            news_que = XlzNews.objects.filter(user_id=user_id).order_by('-update_time').first()
            # 保存图片文件，返回图片的字典，{图片名：url}
            if img_list is not None:
                img_lists = my_upload(img_list)
                for num in range(0, 8):
                    if num < len(img_lists):
                        # 保存动态消息
                        XlzImages.objects.create(img_url=img_lists[num], news_id=news_que.id, site_tag=site_tag[num],
                                                 brand_tag=brand_tag[num], diy_tag=diy_tag[num], site_tag_location=site_location[num],
                                                 brand_tag_location=brand_location[num], diy_tag_location=diy_location[num])

            return Response({'code': RET.OK, 'msg': "请求成功"})

        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code":  RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-自定义标签搜索
class DsearchView(APIView):

    def get(self, request):
        try:
            dsearch_content = request.query_params.get('search_content')
            if dsearch_content:
                result = XlzImages.objects.filter(diy_tag__icontains=dsearch_content)
                if result:
                    diy_tags = []
                    for diy_tag in result:
                        diy_tags.append(diy_tag.diy_tag)
                    return Response({
                        'code': RET.OK,
                        'msg': error_map[RET.OK],
                        'data': {
                            'data': diy_tags,
                        },
                    })
                return Response({
                    'code': RET.CREATE_LABEL_OK,
                    'msg': error_map[RET.CREATE_LABEL_OK],
                    'data': {
                        'search_content':dsearch_content,
                    },
                })
            return Response({
                'code': error_map[RET.NODATA],
                'msg': RET.NODATA,
                'data': {
                    'data': {},
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-话题搜索
class TsearchView(APIView):
    serializer = TopicSerializer
    def get(self, request):
        try:
            search_content = request.query_params.get('search_content')
            topic_queryset = XlzTopic.objects.order_by('-create_time')[:15]
            topic_data = self.serializer(topic_queryset,many=True)
            if search_content:
                result = XlzTopic.objects.filter(content__icontains=search_content)
                if result:
                    topic_data = self.serializer(result, many=True)
                    return Response({
                        'code': RET.OK,
                        'msg': error_map[RET.OK],
                        'data': {
                            'data': topic_data.data,
                        },
                    })
                else:
                    user_id = request.user.id
                    print(user_id, type(user_id))
                    news_id = XlzNews.objects.filter(user_id=user_id).order_by('-update_time').first()
                    topic = XlzTopic.objects.create(content=search_content,join_user_id=user_id,
                                        create_time=datetime.datetime.now(),news_id=news_id.id)
                    return Response({
                        'code': RET.CREATE_TOPIC_OK,
                        'msg': error_map[RET.CREATE_TOPIC_OK],
                        'data': {
                            'data': {},
                        },
                    })
            return Response({
                'code': error_map[RET.OK],
                'msg': RET.OK,
                'data': {
                    'data': topic_data.data,
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-地点标签搜索
class SsearchView(APIView):
    def get(self,request):
        try:
            ssearch_content = request.query_params.get('search_content')
            if ssearch_content:
                result = XlzImages.objects.filter(site_tag__icontains=ssearch_content)
                if result:
                    site_tags = []
                    for site_tag in result:
                        site_tags.append(site_tag.site_tag)
                    return Response({
                        'code': RET.OK,
                        'msg': error_map[RET.OK],
                        'data': {
                            'data': site_tags,
                        },
                    })
                else:
                    return Response({
                        'code': RET.CREATE_LABEL_OK,
                        'msg': error_map[RET.CREATE_LABEL_OK],
                        'data': {
                            'search_content': ssearch_content,
                        },
                    })
            return Response({
                'code': error_map[RET.NODATA],
                'msg': RET.NODATA,
                'data': {
                    'data': {},
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 社区-品牌标签搜索
class BsearchView(APIView):
    def get(self, request):
        try:
            bsearch_content = request.query_params.get('search_content')
            if bsearch_content:
                result = XlzImages.objects.filter(brand_tag__icontains=bsearch_content)
                if result:
                    brand_tags = []
                    for brand_tag in result:
                        brand_tags.append(brand_tag.brand_tag)
                    return Response({
                        'code': RET.OK,
                        'msg': error_map[RET.OK],
                        'data': {
                            'data': brand_tags,
                        },
                    })
                else:
                    return Response({
                        'code': RET.CREATE_LABEL_OK,
                        'msg': error_map[RET.CREATE_LABEL_OK],
                        'data': {
                            'search_content': bsearch_content,
                        },
                    })
            return Response({
                'code': error_map[RET.NODATA],
                'msg': RET.NODATA,
                'data': {
                    'data': {},
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 提醒用户记账
class ReminderbookkeepingView(APIView):
    serializer = ReminderbookkeepingSerializer

    def get(self, request):
        try:
            user_id = request.user.id
            time_queryset = XlzRemind.objects.filter(user_id=user_id)
            # 序列化
            if time_queryset:
                time_data = self.serializer(time_queryset, many=True)
                return Response({
                        'code': RET.OK,
                        'msg': error_map[RET.OK],
                        'data': {
                            'data': time_data.data,
                        },
                    })
            return Response({
                'code': RET.NODATA,
                'msg': error_map[RET.NODATA],
                'data': {
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})



    def post(self,request):
        try:
            user_id = request.user.id
            remind_time = request.POST.get('remind_time')
            if remind_time:
                remind_time = datetime.datetime.strptime(remind_time, "%H:%M")
                XlzRemind.objects.create(user_id=user_id, remind_time=remind_time)
                return Response({
                        'code': RET.OK,
                        'msg': error_map[RET.OK],
                        'data': {
                        },
                    })
            return Response({
                'code': RET.NODATA,
                'msg': error_map[RET.NODATA],
                'data': {
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})

    def patch(self, request):
        try:
            user_id = request.user.id
            id = request.POST.get('id')
            del_time = XlzRemind.objects.filter(user_id=user_id,id=id)
            if del_time:
                del_time.delete()
                return Response({
                    'code': RET.OK,
                    'msg': error_map[RET.OK],
                    'data': {
                    },
                })
            return Response({
                'code': RET.NODATA,
                'msg': error_map[RET.NODATA],
                'data': {
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 新增关注提醒
class AMessagealertView(APIView):
    serializer = FansSerializer
    def get(self, request):
        try:
            context = {
                "request": request,
            }
            user_id = request.user.id
            # 获取用户的关注列表
            att_queryset = XlzAttention.objects.filter(user_id=user_id)
            # 序列化
            if att_queryset:
                news_data = self.serializer(att_queryset, many=True, context=context)
                return Response({
                    'code': RET.OK,
                    'msg': error_map[RET.OK],
                    'data': {
                        'data': news_data.data,
                    },
                })
            return Response({
                'code': RET.NODATA,
                'msg': error_map[RET.NODATA],
                'data': {
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 新评论消息提醒
class CMessagealertView(APIView):
    serializer = CommentSerializer
    def get(self, request):
        try:
            user_id = request.user.id
            # 获取用户的被评论的文章列表
            res = XlzNews.objects.filter(user_id__exact=user_id).values('id')
            att_queryset = XlzReplay.objects.filter(comment_id__in=res)
            if att_queryset:
                news_data = self.serializer(att_queryset, many=True)
                return Response({
                    'code': RET.OK,
                    'msg': error_map[RET.OK],
                    'data': {
                        'data': news_data.data,
                    },
                })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})


# 用户点击话题，跳转话题相关动态
class ShowdetailsView(APIView):
    queryset = XlzNews.objects.all()
    serializer = NewestSerializer

    def get(self, request):
        try:
            context = {
                "request": request,
            }
            topic_content = request.query_params.get('topic_content')
            topic_queryset = XlzTopic.objects.filter(content=topic_content)
            news_queryset = XlzNews.objects.filter(topic_id=topic_queryset[0].news_id)[:6]

            if news_queryset:
                topic_data = self.serializer(news_queryset, context=context, many=True)
                return Response({
                        'code': RET.OK,
                        'msg': error_map[RET.OK],
                        'data': {
                            'data': topic_data.data,
                        },
                    })
            return Response({
                'code': error_map[RET.NODATA],
                'msg': RET.NODATA,
                'data': {
                    'data': {},
                },
            })
        except Exception as e:
            print(e)
            raise AuthenticationFailed({"code": RET.PARAMERR, "msg": error_map[RET.PARAMERR]})
